import { UseOptions } from '../../interface/cmd'
import { RequestBody, ResponsesTnd, SwaggerDocTnd, UsePaths } from '../../interface/swagger'
import { TranslationNumber, extractContent, removeComponenStr, removeDoubblerowStr } from '../../utils'
import { handleSchema } from './common'
export interface PathsChildTnd {
  tags: string[]
  requestBody: RequestBody
  summary: string
  consumes: string[]
  responses: ResponsesTnd
}
export default function handlePathsTnd(file: SwaggerDocTnd, option: UseOptions) {
  const paths = file.paths
  const result: UsePaths[] = []
  Object.keys(paths).forEach((uri) => {
    const method = Object.keys(paths[uri])[0]
    const pathItem = paths[uri][method]
    const tags = pathItem.tags[0]
    let params = handlePathTndParameters(pathItem)
    params = params? removeComponenStr(params): undefined
    const response  =handlePathTndResponse(pathItem,option.resKey)
    result.push({
      url: uri,
      method: method,
      tags: tags,
      summary: pathItem.summary,
      params: params,
      response: response,
      required: false
    })
  })
  return result
}

function handlePathTndParameters(pathItem: PathsChildTnd) {
  const contentKey = Object.keys(pathItem.requestBody['content'])[0]
  const contentItem = pathItem.requestBody['content'][contentKey].schema
  return handleSchema(contentItem)
}

function handlePathTndResponse(pathItem: PathsChildTnd, resKey: string) {
  if (!pathItem.responses) {
    console.error('error response')
  }
  const responseItem = pathItem.responses[`${resKey}`].content
  const content = responseItem[`${Object.keys(responseItem)[0]}`]
  let res = handleSchema(content.schema)
  res = removeComponenStr(res!)
  let resContent = extractContent(res!) || res
  if (resContent && resContent.includes('«')) {
    // 存在List情况
    let List = removeDoubblerowStr(resContent!, 2)
    List = TranslationNumber(List)
    return `${List}[]`
  } else {
    resContent = resContent ? TranslationNumber(resContent!) : resContent
    return resContent
  }
}